/**
 * 依赖:mui,nativeShare
 * 使用方法:
 * new Share('#shareBox',{
        url : shareArticleURL,//分享地址
        title : data.Title,//标题
        content : data.Content,//内容
        login : !app.isLogin(),//是否提示先登录
        loginUrl : serverurl+'g=Admin&m=Public&a=login',//登录地址
        icon : shareLogo,//分享图标
   });
 */

(function(mod) {
    if (typeof exports == "object" && typeof module == "object") // CommonJS
        module.exports = mod();
    else if (typeof define == "function" && define.amd) // AMD
        return define([], mod);
    else // Plain browser env
        this.Share = mod();
})(function() {


    function getElement(elem){
        console.log(elem.indexOf('#'));
        var element = null;
        if(elem.indexOf('#') === 0){
            element = byId(elem.substring(1));
        }else if(elem.indexOf('.') === 0){
            element = byClass(elem.substring(1));
        }else{
            element = byTagName(elem);
        }

        function byId(id) {
            return document.getElementById(id);
        }
        function byClass(clsName, oParent) {
            var boxArr = new Array();
            var oElements  = (oParent ? document.getElementById(oParent):document.body).getElementsByTagName('*');
            for(var i=0;i<oElements.length;i++){
                if(oElements[i].className == clsName){
                    boxArr.push(oElements[i]);
                }
            }
            if(boxArr.length == 1){
                boxArr = boxArr[0];
            }
            return boxArr;
        }
        function byTagName(elem, obj) {
            var element = (obj || document).getElementsByTagName(elem);
            if(element.length == 1){
                element = element[0];
            }
            return element;
        }
        return element;
    }

    var popHtml = '<div id="popover" class="mui-popover">' +
        '<div class="gb_resLay">' +
        '<div class="gb_res_t"><span>分享到</span><i></i></div>' +
        '<div class="bdsharebuttonbox">' +
        '<ul class="gb_resItms">' +
        '<li> <a title="分享到微信" href="#" class="bds_weixin" data-cmd="weixin"></a>微信好友</li>' +
        '<li> <a title="分享到QQ好友" href="#" class="bds_sqq" data-cmd="sqq"></a>QQ好友</li>' +
        '<li> <a title="分享到QQ空间" href="#" class="bds_qzone" data-cmd="qzone"></a>QQ空间</li>' +
        '<li> <a title="分享到腾讯微博" href="#" class="bds_tqq" data-cmd="tqq"></a>腾讯微博</li>' +
        '<li> <a title="分享到新浪微博" href="#" class="bds_tsina" data-cmd="tsina"></a>新浪微博</li>' +
        '<li> <a title="分享到人人网" href="#" class="bds_renren" data-cmd="renren"></a>人人网</li>' +
        '</ul>' +
        '</div>' +
        '</div>' +
        '</div>';
    popHtml += '<div class="mui-backdrop" style=""></div>';

    function Share(elem,options){
        //console.log(get.byId(elem));
        var option = extend(defaults,options);
        var element = getElement(elem);
        console.log(element);
        this._init(element,option);
    }

    var defaults = {
        url : '',
        title : '',
        content : '',
        login : false,
        loginUrl:'',
        icon : ''
    };

    var extend=function(o,n){
        var options = new Object();
        if(o){
            for (var p in o){
                if(o.hasOwnProperty(p))
                    options[p]=o[p];
            }
        }
        if(n){
            for (var p in n){
                if(n.hasOwnProperty(p))
                    options[p]=n[p];
            }
        }
        return options;
    };

    function isWeiXin() {
        var ua = window.navigator.userAgent.toLowerCase();
        console.log(ua);//mozilla/5.0 (iphone; cpu iphone os 9_1 like mac os x) applewebkit/601.1.46 (khtml, like gecko)version/9.0 mobile/13b143 safari/601.1
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
            return true;
        } else {
            return false;
        }
    }

    Share.prototype._showLogin = function(options,nativeShare){
        var share = this;
        var btnArray = ['否', '是'];
        mui.confirm('登录后分享可以获取更多收益', '是否登录？', btnArray, function(e) {
            if (e.index == 1) {
                if(options.loginUrl){
                    window.location.href = options.loginUrl;
                }
            } else {
                try {
                    if(isWeiXin()){
                        mui.toast('请点击右上角位置进行分享～');
                    }else{
                        nativeShare.call();
                    }
                } catch (err) {
                    share._show();
                }
                //share._show();
            }
        })
    };
    Share.prototype._init = function(elem,options){
        var share = this;

        window._bd_share_config = {
            "common": {
                'bdUrl':options.url,
                "bdSnsKey": {},
                "bdText": options.title,
                "bdDesc": options.content,
                "bdMini": "2",
                "bdMiniList": false,
                "bdPic": options.icon,
                "bdStyle": "0",
                "bdSize": "24"
            }, "share": {}
        };

        var nativeShare = new NativeShare();
        var share_Data = {
            title: options.title,
            desc: options.content,
            // 如果是微信该link的域名必须要在微信后台配置的安全域名之内的。
            link: options.bdUrl,
            icon: options.icon,
            // 不要过于依赖以下两个回调，很多浏览器是不支持的
            success: function() {
                //alert('success')
            },
            fail: function() {
                //alert('fail')
            }
        };
        nativeShare.setShareData(share_Data);

        var popHtml = document.createElement('div');
        popHtml.setAttribute('id','share_popover');
        popHtml.setAttribute('class','mui-popover');
        var gb_resLay = document.createElement('div');
        gb_resLay.setAttribute('class','gb_resLay');

        var gb_res_t = document.createElement('div');
        gb_res_t.setAttribute('class','gb_res_t');
        var span = document.createElement('span');
        var spanText = document.createTextNode('分享到');
        span.appendChild(spanText);
        gb_res_t.appendChild(span);
        gb_resLay.appendChild(gb_res_t);

        var bdsharebuttonbox = document.createElement('div');
        bdsharebuttonbox.setAttribute('class','bdsharebuttonbox');
        var ul = document.createElement('ul');
        ul.setAttribute('class','gb_resItms');
        //微信
        var li_weixin = document.createElement('li');
        var a_weixin = document.createElement('a');
        a_weixin.setAttribute('title','分享到微信');
        a_weixin.setAttribute('class','bds_weixin');
        a_weixin.setAttribute('data-cmd','weixin');
        var li_weixin_Text = document.createElement('微信好友');
        li_weixin.appendChild(a_weixin);
        li_weixin.appendChild(li_weixin_Text);
        //QQ
        var li_qq = document.createElement('li');
        var a_qq = document.createElement('a');
        a_qq.setAttribute('title','分享到QQ好友');
        a_qq.setAttribute('class','bds_sqq');
        a_qq.setAttribute('data-cmd','sqq');
        var li_qq_Text = document.createElement('QQ好友');
        li_qq.appendChild(a_qq);
        li_qq.appendChild(li_qq_Text);
        //QQ空间
        var li_qzone = document.createElement('li');
        var a_qzone = document.createElement('a');
        a_qzone.setAttribute('title','分享到QQ空间');
        a_qzone.setAttribute('class','bds_qzone');
        a_qzone.setAttribute('data-cmd','qzone');
        var li_qzone_Text = document.createElement('QQ空间');
        li_qzone.appendChild(a_qzone);
        li_qzone.appendChild(li_qzone_Text);
        //腾讯微博
        var li_tqq = document.createElement('li');
        var a_tqq = document.createElement('a');
        a_tqq.setAttribute('title','分享到腾讯微博');
        a_tqq.setAttribute('class','bds_tqq');
        a_tqq.setAttribute('data-cmd','tqq');
        var li_tqq_Text = document.createElement('腾讯微博');
        li_tqq.appendChild(a_tqq);
        li_tqq.appendChild(li_tqq_Text);
        //新浪微博
        var li_tsina = document.createElement('li');
        var a_tsina = document.createElement('a');
        a_tsina.setAttribute('title','分享到新浪微博');
        a_tsina.setAttribute('class','bds_tsina');
        a_tsina.setAttribute('data-cmd','tsina');
        var li_tsina_Text = document.createElement('新浪微博');
        li_tsina.appendChild(a_tsina);
        li_tsina.appendChild(li_tsina_Text);
        //人人网
        var li_renren = document.createElement('li');
        var a_renren = document.createElement('a');
        a_renren.setAttribute('title','分享到人人网');
        a_renren.setAttribute('class','bds_renren');
        a_renren.setAttribute('data-cmd','renren');
        var li_renren_Text = document.createElement('人人网');
        li_renren.appendChild(a_renren);
        li_renren.appendChild(li_renren_Text);

        ul.appendChild(li_weixin);
        ul.appendChild(li_qq);
        ul.appendChild(li_qzone);
        ul.appendChild(li_tqq);
        ul.appendChild(li_tsina);
        ul.appendChild(li_renren);
        bdsharebuttonbox.appendChild(ul);
        gb_resLay.appendChild(bdsharebuttonbox);

        popHtml.appendChild(gb_resLay);

        popHtml.style.display = 'none';
        document.body.appendChild(popHtml);
        var mui_backdrop = document.createElement('div');
        mui_backdrop.setAttribute('class','mui-backdrop');
        mui_backdrop.style.display = 'none';
        document.body.appendChild(mui_backdrop);
        with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];

        elem.addEventListener('touchstart',function(){
            console.log('点击');
            //判断是否登录提示
            //判断是否微信
            if(options.login) {
                share._showLogin(options,nativeShare);
            }else if(isWeiXin()){
                mui.toast('请点击右上角位置进行分享～');
            }else{
                try {
                    nativeShare.call();
                } catch (err) {
                    share._show();
                }
            }
        });
    };

    Share.prototype._show = function(){
        var share = this;

        getElement('#share_popover').style.display = 'block';
        getElement('.mui-backdrop').style.display = 'block';
        getElement('.mui-backdrop').addEventListener('touchstart',function(){
            console.log('touchstart');
            share._hide();
        });
    };
    Share.prototype._hide = function(){
        var share = this;
        getElement('#share_popover').style.display = 'none';
        getElement('.mui-backdrop').style.display = 'none';
    };

    return Share;
});